package com.ysd.lis.service.samsto.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabProcessSet;
import com.ysd.lis.entity.lab.LabReqMain;
import com.ysd.lis.entity.lab.LabReqState;
import com.ysd.lis.entity.samsto.SamstoSpecbox;
import com.ysd.lis.entity.samsto.SamstoSpecboxOrder;
import com.ysd.lis.entity.samsto.SamstoSpecboxOrderReq;
import com.ysd.lis.mapper.lab.LabProcessSetMapper;
import com.ysd.lis.mapper.lab.LabReqStateMapper;
import com.ysd.lis.mapper.samsto.SamstoSpecboxOrderMapper;
import com.ysd.lis.mapper.samsto.SamstoSpecboxOrderReqMapper;
import com.ysd.lis.request.samsto.SamstoSpecboxVo;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.lis.service.lab.LabReqMainService;
import com.ysd.lis.service.samsto.SamstoSpecboxOrderReqService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 仓位-申请表 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-11-13
 */
@Service
public class SamstoSpecboxOrderReqServiceImpl extends ServiceImpl<SamstoSpecboxOrderReqMapper, SamstoSpecboxOrderReq> implements SamstoSpecboxOrderReqService {

    @Autowired
    private SamstoSpecboxOrderMapper samstoSpecboxOrderMapper;

    @Autowired
    private SamstoSpecboxOrderReqService samstoSpecboxOrderReqService;
    @Autowired
    private LabReqMainService labReqMainService;

    @Autowired
    private LabMaininfoService labMaininfoService;
    @Autowired
    SysBasDictDetailService detailService;
    @Autowired
    LabReqStateMapper labReqStateMapper;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    LabProcessSetMapper processSetMapper;


    @Override
    public Result getReqData(LabReqMain labReqMain) {
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.selectCollection(LabMaininfo.class, LabReqMain::getLabMaininfoList);
        queryWrapper.leftJoin(LabMaininfo.class, LabMaininfo::getReqNo, LabMaininfo::getReqNo);
        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            queryWrapper.eq(LabReqMain::getReqNo, labReqMain.getReqNo());
        }
        LabReqMain labReqMain1 = labReqMainService.selectJoinOne(LabReqMain.class, queryWrapper);
        labReqMain1.setLabMaininfoList(
                labReqMain1.getLabMaininfoList().stream()
                        .sorted(Comparator.comparing(LabMaininfo::getSampleda).reversed())
                        .collect(Collectors.toList())
        );
        List<SysUser> userList = sysUserService.list();
        LabMaininfo maininfo = labReqMain1.getLabMaininfoList().get(0);
        if (StrUtil.isNotEmpty(maininfo.getChkDoctor())) {
            Optional<SysUser> first = userList.stream().filter(a -> maininfo.getChkDoctor().equals(a.getUsername())).findFirst();
            if (first.isPresent()) {
                maininfo.setChkDoctorNa(first.get().getRealname());
            }
        }
        if (StrUtil.isNotEmpty(maininfo.getTestDoctor())) {
            Optional<SysUser> first = userList.stream().filter(a -> maininfo.getTestDoctor().equals(a.getUsername())).findFirst();
            if (first.isPresent()) {
                maininfo.setTestDoctorNa(first.get().getRealname());
            }
        }
        return Result.succ(1, "查询成功", labReqMain1);
    }

    @Override
    public Result getHisReqNoList(SamstoSpecboxOrderReq samstoSpecboxOrderReq) {
        LambdaQueryWrapper<SamstoSpecboxOrderReq> orderReqQueryWrapper = new LambdaQueryWrapper<>();
        orderReqQueryWrapper.eq(SamstoSpecboxOrderReq::getDelFlag, 0);
        orderReqQueryWrapper.eq(SamstoSpecboxOrderReq::getStatus, 10);
        orderReqQueryWrapper.eq(SamstoSpecboxOrderReq::getSpecboxOrderId, samstoSpecboxOrderReq.getSpecboxOrderId());
        orderReqQueryWrapper.orderByDesc(SamstoSpecboxOrderReq::getEnterTime);
        List<SamstoSpecboxOrderReq> samstoSpecboxOrderReqs = this.baseMapper.selectList(orderReqQueryWrapper);
        List<String> reqNos = samstoSpecboxOrderReqs.stream().map(SamstoSpecboxOrderReq::getReqNo).filter(StringUtils::isNotBlank).collect(Collectors.toList());

        List<LabReqMain> reqMainList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(reqNos)) {
            MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(LabReqMain.class);
            queryWrapper.selectCollection(LabMaininfo.class, LabReqMain::getLabMaininfoList);
            queryWrapper.leftJoin(LabMaininfo.class, LabMaininfo::getReqNo, LabMaininfo::getReqNo);
            queryWrapper.eq(LabReqMain::getDelFlag, 0);
            queryWrapper.in(LabReqMain::getReqNo, reqNos);

            reqMainList = labReqMainService.selectJoinList(LabReqMain.class, queryWrapper);
            List<SysUser> userList = sysUserService.list();
            for (LabReqMain reqMain : reqMainList) {
                reqMain.setLabMaininfoList(
                        reqMain.getLabMaininfoList().stream()
                                .sorted(Comparator.comparing(LabMaininfo::getSampleda).reversed())
                                .collect(Collectors.toList())
                );

                LabMaininfo maininfo = reqMain.getLabMaininfoList().get(0);
                if (StrUtil.isNotEmpty(maininfo.getChkDoctor())) {
                    Optional<SysUser> first = userList.stream().filter(a -> maininfo.getChkDoctor().equals(a.getUsername())).findFirst();
                    if (first.isPresent()) {
                        maininfo.setChkDoctorNa(first.get().getRealname());
                    }
                }
                if (StrUtil.isNotEmpty(maininfo.getTestDoctor())) {
                    Optional<SysUser> first = userList.stream().filter(a -> maininfo.getTestDoctor().equals(a.getUsername())).findFirst();
                    if (first.isPresent()) {
                        maininfo.setTestDoctorNa(first.get().getRealname());
                    }
                }
            }
        }
        return Result.succ(1, "查询成功", reqMainList);

    }

    @Override
    public Result getSpecboxOrderReqList(SamstoSpecbox specbox) {
        MPJLambdaWrapper<SamstoSpecboxOrder> infoWrapper = new MPJLambdaWrapper<>();
        infoWrapper.selectAll(SamstoSpecboxOrder.class);
        infoWrapper.selectAs(SamstoSpecboxOrderReq::getReqNo, SamstoSpecboxOrder::getReqNo);
        infoWrapper.selectAs(SamstoSpecboxOrderReq::getStatus, SamstoSpecboxOrder::getReqStatus);
        infoWrapper.leftJoin(SamstoSpecboxOrderReq.class, p -> p.eq(SamstoSpecboxOrderReq::getSpecboxOrderId, SamstoSpecboxOrder::getId).eq(SamstoSpecboxOrderReq::getDelFlag, 0).and(it->it.eq(SamstoSpecboxOrderReq::getStatus, 5).or().eq(SamstoSpecboxOrderReq::getStatus, 15)));
        infoWrapper.eq(SamstoSpecboxOrder::getSpecboxId, specbox.getId());
        List<SamstoSpecboxOrder> samstoSpecboxOrders = samstoSpecboxOrderMapper.selectJoinList(SamstoSpecboxOrder.class, infoWrapper);

        List<String> orderRows = samstoSpecboxOrders.stream().map(SamstoSpecboxOrder::getOrderRow).distinct().sorted(Comparator.comparingInt(Integer::parseInt)).collect(Collectors.toList());
        List<String> orderColumns = samstoSpecboxOrders.stream().map(SamstoSpecboxOrder::getOrderColumn).distinct().sorted().collect(Collectors.toList());
        SamstoSpecboxVo samstoSpecboxVo = new SamstoSpecboxVo();
        samstoSpecboxVo.setOrderRows(orderRows);
        samstoSpecboxVo.setOrderColumns(orderColumns);
        samstoSpecboxVo.setSpecboxOrders(samstoSpecboxOrders);
        return Result.succ(1, "获取信息成功", samstoSpecboxVo);
    }

    @Override
    public Result batchAddOrderReq(List<SamstoSpecboxOrderReq> samstoSpecboxOrderReqs) {
        List<String> orderId = samstoSpecboxOrderReqs.stream().map(SamstoSpecboxOrderReq::getSpecboxOrderId).filter(StringUtils::isNotBlank).collect(Collectors.toList());

        List<SamstoSpecboxOrder> samstoSpecboxOrders = samstoSpecboxOrderMapper.selectList(new LambdaQueryWrapper<SamstoSpecboxOrder>().eq(SamstoSpecboxOrder::getDelFlag, 0).in(SamstoSpecboxOrder::getId, orderId));
        Map<String, List<SamstoSpecboxOrder>> orderMap = samstoSpecboxOrders.stream().collect(Collectors.groupingBy(SamstoSpecboxOrder::getId));

        List<String> reqNos = samstoSpecboxOrderReqs.stream().map(SamstoSpecboxOrderReq::getReqNo).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        List<LabMaininfo> maininfos = labMaininfoService.list(new LambdaQueryWrapper<LabMaininfo>().in(LabMaininfo::getReqNo, reqNos).eq(LabMaininfo::getDelFlag, 0));
        Map<String, List<LabMaininfo>> mainMap = maininfos.stream().collect(Collectors.groupingBy(LabMaininfo::getReqNo));

        for (SamstoSpecboxOrderReq samstoSpecboxOrderReq : samstoSpecboxOrderReqs) {
            SamstoSpecboxOrder samstoSpecboxOrder = orderMap.get(samstoSpecboxOrderReq.getSpecboxOrderId()).get(0);
            samstoSpecboxOrderReq.setOrderNumber(samstoSpecboxOrder.getOrderNumber());
            List<LabMaininfo> labMaininfos = mainMap.get(samstoSpecboxOrderReq.getReqNo());
            String rptGroup = labMaininfos.stream()
                    .map(LabMaininfo::getRptGroup)
                    .filter(Objects::nonNull) // 过滤掉 null 值
                    .collect(Collectors.joining(","));
            samstoSpecboxOrderReq.setRptGroup(rptGroup);
        }

        //仓位设置 为放置
        LambdaUpdateWrapper<SamstoSpecboxOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper
                .set(SamstoSpecboxOrder::getEmpty, 1)
                .in(SamstoSpecboxOrder::getId, orderId);
        samstoSpecboxOrderMapper.update(null, lambdaUpdateWrapper);

        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "160");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        LambdaUpdateWrapper<LabReqMain> reqMainLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        reqMainLambdaUpdateWrapper
                .set(LabReqMain::getState, "160")
                .set(LabReqMain::getIsStore, 1)
                .set(LabReqMain::getStateNa, value)
                .in(LabReqMain::getReqNo, reqNos);
        labReqMainService.update(null, reqMainLambdaUpdateWrapper);
        //存到状态表中
        SysUser user = RedisUserManager.getUser();
        for (String reqNo : reqNos) {
            LabReqState labReqState = new LabReqState();
            LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
            queryStateWrapper.eq(LabReqState::getReqNo, reqNo).eq(LabReqState::getOrgId, user.getOrgId())
                    .eq(LabReqState::getDelFlag, 0);
            List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
            labReqState.setSeq((long) (listState.size() + 1));
            labReqState.setOrgId(user.getOrgId());
            labReqState.setReqNo(reqNo);
            labReqState.setStateValue(value);
            labReqState.setStateCode("160");
            labReqStateMapper.insert(labReqState);
        }

        boolean r = this.saveBatch(samstoSpecboxOrderReqs);
        return r ? Result.succ(1, "插入成功", samstoSpecboxOrderReqs) : Result.fail("插入失败");
    }

    @Override
    public Result batchDistoryReq(List<SamstoSpecboxOrderReq> samstoSpecboxOrderReqs) {
        List<String> reqNos = samstoSpecboxOrderReqs.stream().map(SamstoSpecboxOrderReq::getReqNo).filter(StringUtils::isNotBlank).collect(Collectors.toList());

        List<SamstoSpecboxOrderReq> samstoSpecboxOrderReqs1 = this.baseMapper.selectList(new LambdaQueryWrapper<SamstoSpecboxOrderReq>().eq(SamstoSpecboxOrderReq::getDelFlag, 0).in(SamstoSpecboxOrderReq::getReqNo, reqNos).and(p -> p.eq(SamstoSpecboxOrderReq::getStatus, 5).or().eq(SamstoSpecboxOrderReq::getStatus, 15)));
        List<String> orderId = samstoSpecboxOrderReqs1.stream().map(SamstoSpecboxOrderReq::getSpecboxOrderId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        samstoSpecboxOrderReqs1.forEach(x -> x.setStatus(BigDecimal.valueOf(10)));
        samstoSpecboxOrderReqService.saveOrUpdateBatch(samstoSpecboxOrderReqs1);

        //仓位设置 为放置
        LambdaUpdateWrapper<SamstoSpecboxOrder> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper
                .set(SamstoSpecboxOrder::getEmpty, 0)
                .in(SamstoSpecboxOrder::getId, orderId);
        samstoSpecboxOrderMapper.update(null, lambdaUpdateWrapper);

        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "190");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }

        //修改申请表信息状态
        LambdaUpdateWrapper<LabReqMain> reqMainLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        reqMainLambdaUpdateWrapper
                .set(LabReqMain::getState, "190")
                .set(LabReqMain::getIsStore, 1)
                .set(LabReqMain::getStateNa, value)
                .in(LabReqMain::getReqNo, reqNos);
        labReqMainService.update(null, reqMainLambdaUpdateWrapper);
        //存到状态表中
        SysUser user = RedisUserManager.getUser();

        for (String reqNo : reqNos) {
            LabReqState labReqState = new LabReqState();
            LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
            queryStateWrapper.eq(LabReqState::getReqNo, reqNo).eq(LabReqState::getOrgId, user.getOrgId())
                    .eq(LabReqState::getDelFlag, 0);
            List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
            labReqState.setSeq((long) (listState.size() + 1));
            labReqState.setOrgId(user.getOrgId());
            labReqState.setReqNo(reqNo);
            labReqState.setStateValue(value);
            labReqState.setStateCode("190");
            labReqStateMapper.insert(labReqState);
        }

            return Result.succ(1, "销毁成功", samstoSpecboxOrderReqs);
    }

    @Override
    public Result sampleLend(LabReqMain labReqMain) {
        try {
            //修改申请表信息状态
            LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
            processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
            processSetWrapper.eq(LabProcessSet::getCode, "170");
            List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

            String value = "";
            if (CollectionUtils.isNotEmpty(processSets)) {
                value = processSets.get(0).getNodeName();
            }
            LambdaUpdateWrapper<LabReqMain> reqMainLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            reqMainLambdaUpdateWrapper
                    .set(LabReqMain::getState, "170")
                    .set(LabReqMain::getIsStore, 1)
                    .set(LabReqMain::getStateNa, value)
                    .eq(LabReqMain::getReqNo, labReqMain.getReqNo());
            labReqMainService.update(null, reqMainLambdaUpdateWrapper);
            //存到状态表中
            SysUser user = RedisUserManager.getUser();

            LabReqState labReqState = new LabReqState();
            LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
            queryStateWrapper.eq(LabReqState::getReqNo, labReqMain.getReqNo()).eq(LabReqState::getOrgId, user.getOrgId())
                    .eq(LabReqState::getDelFlag, 0);
            List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
            labReqState.setSeq((long) (listState.size() + 1));
            labReqState.setOrgId(user.getOrgId());
            labReqState.setReqNo(labReqMain.getReqNo());
            labReqState.setStateValue(value);
            labReqState.setStateCode("170");
            labReqStateMapper.insert(labReqState);

            String orderId =  labReqMain.getSamstoSpecboxOrderReqId();

            LambdaUpdateWrapper<SamstoSpecboxOrderReq> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(SamstoSpecboxOrderReq::getStatus,15);
            wrapper.eq(SamstoSpecboxOrderReq::getId,orderId);
            samstoSpecboxOrderReqService.update(wrapper);

            return Result.succ(1, "借出成功", labReqMain);
        } catch (Exception e) {
            return Result.fail(500, e.toString(), "借出失败");
        }


    }

    @Override
    public Result sampleGiveBack(LabReqMain labReqMain) {
        try {
            //修改申请表信息状态
            LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
            processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
            processSetWrapper.eq(LabProcessSet::getCode, "180");
            List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

            String value = "";
            if (CollectionUtils.isNotEmpty(processSets)) {
                value = processSets.get(0).getNodeName();
            }
            LambdaUpdateWrapper<LabReqMain> reqMainLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            reqMainLambdaUpdateWrapper
                    .set(LabReqMain::getState, "180")
                    .set(LabReqMain::getIsStore, 1)
                    .set(LabReqMain::getStateNa, value)
                    .eq(LabReqMain::getReqNo, labReqMain.getReqNo());
            labReqMainService.update(null, reqMainLambdaUpdateWrapper);
            //存到状态表中
            SysUser user = RedisUserManager.getUser();

            LabReqState labReqState = new LabReqState();
            LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
            queryStateWrapper.eq(LabReqState::getReqNo, labReqMain.getReqNo()).eq(LabReqState::getOrgId, user.getOrgId())
                    .eq(LabReqState::getDelFlag, 0);
            List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
            labReqState.setSeq((long) (listState.size() + 1));
            labReqState.setOrgId(user.getOrgId());
            labReqState.setReqNo(labReqMain.getReqNo());
            labReqState.setStateValue(value);
            labReqState.setStateCode("180");
            labReqStateMapper.insert(labReqState);

            String orderId =  labReqMain.getSamstoSpecboxOrderReqId();

            LambdaUpdateWrapper<SamstoSpecboxOrderReq> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(SamstoSpecboxOrderReq::getStatus,5);
            wrapper.eq(SamstoSpecboxOrderReq::getId,orderId);
            samstoSpecboxOrderReqService.update(wrapper);

            return Result.succ(1, "归还成功", labReqMain);
        } catch (Exception e) {
            return Result.fail(500, e.toString(), "归还失败");
        }
    }
}
